<template>
  <ly-dialog
    v-model="visible"
    :title="$t('route.Steam') + '--' +'新增'"
    width="1250px"
    fullscreen
    :confirm="handleConfirm"
    :cancel="handleCancel"
    :before-close="() => {$emit('update:visible', false)}"
    @open="handleOpen"
  >
    <template #operation>
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handlePush()"
      >增加一行</el-button>
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handleCopy()"
      >复制一行</el-button>
      <el-button
        type="primary"
        icon="el-icon-delete"
        class="deleted-button"
        @click="handleBatchDelete()"
      >
        批量删除
      </el-button>
    </template>
    <ly-form
      size="mini"
      class="mini-form"
      style="width:100%"
      :model="temp"
      @submit.native.prevent
    >
      <el-row>
        <el-col :span="5">
          <el-form-item
            label="采购日期"
            prop="orderDate"
          >
            <el-date-picker
              v-model="temp.orderDate"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item
            label="进展"
            prop="progress"
          >
            <el-select
              v-model="temp.progress"
              clearable
              placeholder="请选择进展"
              @change="handleChange"
            >
              <el-option
                v-for="item in progressList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item
            label="修改日期"
            prop="modifyTime"
          >
            <el-date-picker
              v-model="temp.modifyTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </ly-form>
    <client-table
      ref="table"
      :style="{ height: `${commonLayoutHeight}px`}"
      :columns="steamAddColumnDef"
      :data="tableData"
      @selection-change="handleSelectionChange"
      @cell-value-changed="handleCellValueChanged"
    />
  </ly-dialog>
</template>

<script>
import NP from 'number-precision'
import { mapState } from 'vuex'
import { addOne } from '@/api/moveBrick'

export default {
  name: 'SteamAddDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: undefined
    },
    progressList: {
      type: Array,
      default: undefined
    }
  },
  data() {
    return {
      temp: {
        orderDate: '',
        modifyTime: '',
        progress: '',
        progressName: ''
      },
      restTemp: {
        orderDate: '',
        modifyTime: '',
        progress: '',
        progressName: ''
      },
      tableData: [],
      multipleSelection: [],
      steamAddColumnDef: [
        {
          headerName: '买入道具名称',
          field: 'itemName',
          type: 'stringColumn'
        },
        {
          headerName: 'buff出售价格(元)',
          field: 'sellingPrice',
          showSummary: true,
          type: 'numberColumn'
        },
        {
          headerName: '实际利润(元)',
          field: 'actualProfit',
          showSummary: true
        },
        {
          headerName: 'buff卖出价格($)',
          field: 'buffPrice',
          showSummary: true,
          type: 'numberColumn',
          headerClass: 'my-class'
        },
        {
          headerName: 'steam求购价格($)',
          field: 'steamPrice',
          type: 'numberColumn',
          showSummary: true,
          headerClass: 'my-class'
        },
        {
          headerName: '余额变现的折扣',
          field: 'realizationDiscount'
        },
        {
          headerName: '卡价充值价格',
          field: 'rechargePrice',
          type: 'numberColumn',
          headerClass: 'my-class'
        },
        {
          headerName: '100美金对人民币汇率',
          field: 'exchangeRate',
          type: 'numberColumn',
          headerClass: 'my-class'
        },
        {
          headerName: '余额的充值折扣',
          field: 'rechargeDiscount'
        },
        {
          headerName: '税前100美金余额的利润',
          field: 'profits'
        },
        {
          headerName: '税率',
          field: 'taxRate'
        },
        {
          headerName: '税后利润',
          field: 'aftertaxProfit'
        },
        {
          headerName: '利润率(%)',
          field: 'profitMargin'
        }
      ]
    }
  },
  computed: {
    ...mapState('app', {
      commonLayoutHeight: state => state.height.clientHeight - 190
    })
  },
  methods: {
    handleOpen() {
      this.tableData = []
      this.temp = Object.assign({}, this.restTemp)
      setTimeout(() => {
        this.handlePush()
      }, 200)
      // 键盘绑定事件
      const that = this
      document.addEventListener('keydown', that.bindingKeydown)
    },
    async handleConfirm() {
      const steamLists = this.$refs.table.getData()
      const list = steamLists.filter(item => item.buffPrice === '' && item.steamPrice === '' && item.rechargePrice === '' && item.exchangeRate === '')
      if (list.length > 0) {
        return this.$message({
          showClose: true,
          message: '必选项未填！！！',
          type: 'warning',
          center: true
        })
      }
      const params = {
        orderDate: this.temp.orderDate,
        progress: this.temp.progress,
        progressName: this.temp.progressName,
        steamLists
      }
      const result = await addOne('getSteamAdd', params)
      if (result.code === 200) {
        this.setVisible(false)
        this.$notify({
          title: '成功',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
        this.$emit('add-data')
      }
    },
    // 下键事件
    bindingKeydown(event) {
      if (event.code === 'ArrowDown') {
        this.handleCopy()
      }
    },
    // 新增
    handlePush() {
      const addRow = this.steamAddColumnDef.reduce((acc, curr) => {
        acc[curr.field] = ''
        return acc
      }, {})
      const addRows = [addRow]
      addRows[0].taxRate = '0.035'
      this.$refs.table.addRows(addRows)
      this.$refs.table.redrawRows()
      this.$refs.table.selectRow(addRow)
    },
    // 复制
    handleCopy() {
      const addRow = Object.assign({}, this.multipleSelection[0])
      const addRows = [addRow]
      this.$refs.table.addRows(addRows)
      this.$refs.table.redrawRows()
      this.$refs.table.selectRow(addRow)
    },
    // 删除
    handleBatchDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          showClose: true,
          message: '请勾选要删除项',
          type: 'warning',
          center: true
        })
        return
      }
      this.$refs.table.removeRows(this.multipleSelection)
    },
    // 双击修改
    handleCellValueChanged(e) {
      // 计算规则
      // 实际利润 = buff出售价格 — steam求购价格 * (卡价充值价格 / 100)
      // 余额变现的折扣 = buff卖出价格 / steam求购价格
      // 余额的充值折扣 = 卡价充值价格 / 100美金对人民币汇率
      // 税前100美金余额的利润 = (余额变现的折扣 — 余额的充值折扣) * 100 * (100美金对人民币汇率 / 100)
      // 税后利润 = 税前100美金余额的利润 — （税前100美金余额的利润 * 税率）
      // 利润率 = 卡价充值价格 / 税后利润
      if (e.value !== e.oldValue) {
        e.data.sellingPrice = NP.round(e.data.sellingPrice, 2)
        e.data.buffPrice = NP.round(e.data.buffPrice, 2)
        e.data.taxRate = NP.round(e.data.taxRate, 3)
        e.data.actualProfit = NP.round(NP.minus(e.data.sellingPrice, NP.times(e.data.steamPrice, NP.divide(e.data.rechargePrice, 100))), 4)
        e.data.rechargeDiscount = NP.round(NP.divide(e.data.rechargePrice, e.data.exchangeRate), 9)
        e.data.realizationDiscount = NP.round(NP.divide(e.data.buffPrice, e.data.steamPrice), 9)
        e.data.profits = NP.round(NP.times(NP.minus(e.data.realizationDiscount, e.data.rechargeDiscount), e.data.exchangeRate), 7)
        e.data.aftertaxProfit = NP.round(NP.minus(e.data.profits, NP.times(e.data.profits, e.data.taxRate)), 7)
        e.data.profitMargin = NP.round(NP.times(NP.divide(e.data.aftertaxProfit, e.data.rechargePrice), 100), 2) + '%'
        this.$refs.table.redrawRows()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleChange(val) {
      const list = this.progressList.filter(item => item.id === val)
      if (list.length > 0) {
        this.temp.progressName = list[0].name
      }
    },
    handleCancel() {
      this.setVisible(false)
    },
    setVisible(flag) {
      this.$emit('update:visible', flag)
    }
  }
}
</script>

<style>
</style>
